﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tuxedo.Compile
{
	internal class Cast : Expression
	{
		public UnverifiedType Type { get; private set; }
		public Expression Expression { get; private set; }

		public Cast(Expression expression, UnverifiedType type)
		{
			this.Type = type;
			this.Expression = expression;
		}

		public static Cast TryParse(TokenStream tokens)
		{
			int tokenState = tokens.GetCurrentIndex();
			Cast cast = TryParseImpl(tokens);
			if (cast == null)
			{
				tokens.RestoreIndex(tokenState);
			}
			return cast;
		}

		private static Cast TryParseImpl(TokenStream tokens)
		{
			if (!tokens.PopIfPresent("(")) return null;
			UnverifiedType type = UnverifiedType.Parse(tokens, true);
			if (type == null) return null;
			if (!tokens.PopIfPresent(")")) return null;
			Expression expression = Expression.ParseUnaryExpression(tokens, true);
			if (expression == null) return null;
			return new Cast(expression, type);
		}
	}
}
